﻿-- =========================================================================================================
-- Author:		MICHAEL RITACCO
-- Copyright:	2010 MEKHANO GROUP LLC
-- Version:		08/21/2010 1.0
-- =========================================================================================================
CREATE FUNCTION [flcrTM].[TimeWarp_DEVICE_CONFIG_DEPENDENT](@TIME_KEY int, @DEVICE_CONFIG_DEPENDENT_ID int)
RETURNS INT
AS
BEGIN	
	DECLARE 
		@NEED_TIMEWARP INT
		,@MAX_TIMEKEY INT
		,@RET INT
	
	SELECT @NEED_TIMEWARP =	COUNT(*) FROM [FLCRTM].[DEVICE_CONFIG_DEPENDENT]
							WHERE [TIME_KEY] = @TIME_KEY AND [DEVICE_CONFIG_DEPENDENT_ID] = @DEVICE_CONFIG_DEPENDENT_ID
								
	IF @NEED_TIMEWARP >= 1
		BEGIN
			SELECT @RET = @TIME_KEY
		END
	ELSE
		BEGIN
			DECLARE @TIMEWARP_TAB TABLE (TIME_KEY INT)
			
			-- Determine the most recent record.
			SELECT @MAX_TIMEKEY = MAX([TIME_KEY]) FROM [FLCRTM].[DEVICE_CONFIG_DEPENDENT]
								  WHERE [DEVICE_CONFIG_DEPENDENT_ID] = @DEVICE_CONFIG_DEPENDENT_ID
			
			-- Set the history range boundaries.
			INSERT INTO @TIMEWARP_TAB
			SELECT	[TIME_KEY]
			  FROM	[FLCRTM].[DEVICE_CONFIG_DEPENDENT]
			 WHERE	[TIME_KEY] BETWEEN @TIME_KEY AND @MAX_TIMEKEY
			   AND	[DEVICE_CONFIG_DEPENDENT_ID] = @DEVICE_CONFIG_DEPENDENT_ID
			 
			 -- Determine the next closest record in history to set warp target.
			 SELECT @RET = MIN(TIME_KEY) FROM @TIMEWARP_TAB

			-- The future is unknown. Set return value to latest record found.
			IF  @ret IS NULL
				BEGIN
					SELECT @RET = @MAX_TIMEKEY
				END			 
		END

	RETURN @RET			
END